<template>
	<el-dialog v-model="visible" :title="dialogTitle" width="600px" :before-close="handleClose">
		<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
			<el-row :gutter="20">
				<el-col :span="24">
					<el-form-item label="商品码" prop="itemCode">
						<el-autocomplete
							v-model="form.itemCode"
							:fetch-suggestions="queryItemCode"
							clearable
							placeholder="请输入商品码"
							@select="handleItemCodeSelect"
						/>
					</el-form-item>
				</el-col>

				<el-col :span="24">
					<el-form-item label="条形类型" prop="sizeType">
						<el-select v-model="form.sizeType" @change="sizeTypeChange">
							<el-option v-for="item in list" :key="item" :value="item"> </el-option>
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="24">
					<el-form-item label="入库时零售价" prop="retailPrice">
						<el-input-number
							v-model="form.retailPrice"
							:min="0"
							:precision="2"
							placeholder="请输入零售价"
							style="width: 100%"
						/>
					</el-form-item>
				</el-col>

				<!-- 尺码信息列表 -->
				<el-col :span="24" v-if="form.sizeInfoList && form.sizeInfoList.length > 0">
					<el-form-item label="条形码">
						<div style="width: 100%">
							<div
								v-for="(sizeInfo, index) in form.sizeInfoList"
								:key="sizeInfo.barcode"
								style="
									display: flex;
									align-items: center;
									margin-bottom: 10px;
									padding: 10px;
									border: 1px solid #e4e7ed;
									border-radius: 4px;
								"
							>
								<div style="flex: 1; margin-right: 10px">
									{{ sizeInfo.barcode }}
								</div>
								<div style="width: 150px">
									<el-input-number
										v-model="sizeInfo.sizeQuantity"
										:min="0"
										placeholder="数量"
										style="width: 100%"
									/>
								</div>
							</div>
						</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="handleClose">取消</el-button>
				<el-button type="primary" @click="handleSubmit" :loading="loading">
					确定
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { useCool } from '/@/cool';
// import ProductSelect from './product-select.vue';

interface SizeInfo {
	barcode: string;
	sizeQuantity: number;
}

interface StockInRecord {
	id?: number;
	itemCode: string;
	sizeType: string;
	retailPrice: number;
	sizeInfoList: SizeInfo[];
}

interface Product {
	id: number;
	name: string;
	itemCode: string;
	barcode?: string;
	retailPrice?: number;
}

const { service } = useCool();

const visible = ref(false);
const loading = ref(false);
const formRef = ref<FormInstance>();
const mode = ref<'add' | 'edit'>('add');

const form = reactive<StockInRecord>({
	itemCode: '',
	sizeType: '',
	retailPrice: 0,
	sizeInfoList: []
});

// 条码数据
const barCodeData = ref<any>([]);

const list = ref<any>([]);
const barCodeList = ref<any>([]);

const rules: FormRules = {
	itemCode: [{ required: true, message: '请输入商品码', trigger: 'blur' }],
	sizeType: [{ required: true, message: '请选择条形类型', trigger: 'change' }],
	retailPrice: [
		{ required: true, message: '请输入零售价', trigger: 'blur' },
		{ type: 'number', min: 0, message: '零售价不能小于0', trigger: 'blur' }
	]
};

const dialogTitle = computed(() => {
	return mode.value === 'add' ? '新增入库记录' : '编辑入库记录';
});

const emit = defineEmits<{
	success: [];
}>();

// 打开弹窗
const open = (type: 'add' | 'edit', data?: StockInRecord) => {
	mode.value = type;
	visible.value = true;
	getBarCode();
	if (type === 'edit' && data) {
		Object.assign(form, data);
	} else {
		resetForm();
	}
};

// 查找尺码信息
const getBarCode = async () => {
	const data = await service.ling.selectSizeInformation();
	barCodeData.value = data;
	list.value = data.map(item => {
		return item.sizeType;
	});
	updateBarCodeList();
};

// 根据商品类型更新条码列表
const updateBarCodeList = () => {
	const currentSizeType = form.sizeType;
	const foundType = barCodeData.value.find(item => item.sizeType === currentSizeType);
	barCodeList.value = foundType ? foundType.barCodeList : [];

	// 更新表单的 sizeInfoList
	if (foundType && foundType.barCodeList) {
		form.sizeInfoList = foundType.barCodeList.map(barcode => ({
			barcode: barcode,
			sizeQuantity: 0
		}));
	} else {
		form.sizeInfoList = [];
	}
};

const sizeTypeChange = () => {
	updateBarCodeList();
};

// 关闭弹窗
const handleClose = () => {
	visible.value = false;
	resetForm();
};

// 重置表单
const resetForm = () => {
	formRef.value?.resetFields();
	Object.assign(form, {
		itemCode: '',
		sizeType: '',
		retailPrice: 0,
		sizeInfoList: []
	});
};

// 商品码模糊查询
const queryItemCode = (queryString: string, cb: (suggestions: any[]) => void) => {
	if (!queryString) {
		cb([]);
		return;
	}

	// 根据图片中的API路径调用
	service
		.request({
			url: `admin/ling/selectItem/${queryString}`,
			method: 'GET'
		})
		.then((res: string[]) => {
			const suggestions = res.map((item: string) => ({
				value: item,
				label: item
			}));
			cb(suggestions);
		})
		.catch((error: any) => {
			console.error('商品码查询失败:', error);
			// 查询失败时，允许用户直接输入
			cb([{ value: queryString, label: queryString }]);
		});
};

// 选择商品码
const handleItemCodeSelect = (item: any) => {
	form.itemCode = item.value;
};

const searchCode = value => {};

// 提交表单
const handleSubmit = async () => {
	if (!formRef.value) return;

	try {
		await formRef.value.validate();
		loading.value = true;

		if (mode.value === 'add') {
			try {
				await service.ling.addStockInRecord(form);
				ElMessage.success('新增成功');
			} catch (error: any) {
				const message = error.message ? error.message : '操作失败';
				ElMessage.error(message);
			}
		} else {
			// await service.stock.in.record.update(form);
			ElMessage.success('更新成功');
		}
		emit('success');
		handleClose();
	} catch (error) {
		console.error('提交失败:', error);
	} finally {
		loading.value = false;
	}
};

defineExpose({
	open
});
</script>

<style lang="scss" scoped>
.dialog-footer {
	text-align: right;
}
</style>
